import 'package:agent_process_app/pages/aboutUs.dart';
import 'package:agent_process_app/pages/changePwd_screen.dart';
import 'package:agent_process_app/pages/home_screen.dart';
import 'package:agent_process_app/pages/mine_screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:agent_process_app/pages/Login.dart';
import 'package:agent_process_app/pages/MainScreen.dart';
import 'package:agent_process_app/pages/step_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:agent_process_app/utils/myUtils.dart' as myUtils;

main() {
    //渲染界面
    render();
}

render() {
    checkLogin().then((res) {
        print(res.runtimeType);
        print("打开App了!"); //发送请求,记录该用户打开了App,先判断该用户是否有token,如果没有token则不发送该请求
        //判断当前是否为登录状态
        if (res) {
            print("登录状态打开App了!");
            //打开App后发送请求,向服务器报告
            openAppRequest();
            //更新当前用户信息
            updateUserInfo();
            //检查版本更新
            checkVersion();
        }
        runApp(new MyApp(res));
    });
}

checkVersion() async {
    String token;
    await myUtils.LocalStorage.getLocalStorageInstance()
            .then((SharedPreferences sharedPreferences) {
        token = sharedPreferences.getString("token");
    });

    //获取新版本
    Dio dio = myUtils.MyDio.getDio(token);
    Response response;

    //发送打开App请求,在后台记录
    try {
        response = await dio.get(
            "/checkVersion",
        );
        print(response.statusCode);
        print(response.data);
        int statusCode = response.data["Code"];
        //先判断version是否一致, 如果不一致,再将url持久化!!!
        String resVersion = await response.data["Data"]["Version"];
        String resUrl = await response.data["Data"]["Url"];
        if (statusCode == 200) {
            if (resVersion.isNotEmpty &&
                    myUtils.AppInfo.version != resVersion) {
                print(resVersion);
                print("有新版本啦");
                await myUtils.LocalStorage.getLocalStorageInstance()
                        .then((SharedPreferences sharedPreferences) {
                    sharedPreferences.setString("newVersionUrl", resUrl);
                });
            } else {
                //没有更新版本,就存入空字符串
                await myUtils.LocalStorage.getLocalStorageInstance()
                        .then((SharedPreferences sharedPreferences) {
                    sharedPreferences.setString("newVersionUrl", "");
                });
            }
        }
    } catch (e) {
        print(e);
        //在这里判断网络是否正常  2019年2月14日 17:28:25
    }
}

openAppRequest() async {
    String token;
    await myUtils.LocalStorage.getLocalStorageInstance()
            .then((SharedPreferences sharedPreferences) {
        token = sharedPreferences.getString("token");
    });
    Dio dio = myUtils.MyDio.getDio(token);
    Response response;

    //发送打开App请求,在后台记录
    try {
        response = await dio.get(
            "/openApp",
        );
        print(response.statusCode);
    } catch (e) {
        print(e);
        //在这里判断网络是否正常  2019年2月14日 17:28:25
    }
}

updateUserInfo() async {
    String token;
    await myUtils.LocalStorage.getLocalStorageInstance()
            .then((SharedPreferences sharedPreferences) {
        token = sharedPreferences.getString("token");
    });

    Dio dio = myUtils.MyDio.getDio(token);
    Response response = await dio.get("/getUserInfoByToken");

    int resCode = response.data["Code"];
    Map<String, dynamic> resData = response.data["Data"];
    print(resData["Username"]);
    //2019年2月10日 14:37:03 写到这里,写处理的逻辑
    if (resCode == 200) {
        //正确
        if (resData.isNotEmpty) {
            //将username持久化
            await myUtils.LocalStorage.getLocalStorageInstance()
                    .then((SharedPreferences sharedPreferences) {
                sharedPreferences.setString("userName", resData["Username"]);
            });
            //将nickName持久化
            await myUtils.LocalStorage.getLocalStorageInstance()
                    .then((SharedPreferences sharedPreferences) {
                sharedPreferences.setString("nickName", resData["Nickname"]);
            });
            //将头像url持久化
            await myUtils.LocalStorage.getLocalStorageInstance()
                    .then((SharedPreferences sharedPreferences) {
                sharedPreferences.setString("imgUrl", resData["ImgUrl"]);
            });
            //将角色持久化
            await myUtils.LocalStorage.getLocalStorageInstance()
                    .then((SharedPreferences sharedPreferences) {
                sharedPreferences.setString("role", resData["Role"]);
            });
            //根据不同的角色,跳转不同的主页面
        }
    }
}

//检查登录状态
checkLogin() async {
    String token;
    //第一次获取token, token应该是个null值,会报空指针,所以这里需要捕获异常
    try {
        await myUtils.LocalStorage.getLocalStorageInstance()
                .then((SharedPreferences sharedPreferences) {
            token = sharedPreferences.getString("token");
        });
        print(token);
        if (token.isNotEmpty) {
            //进行主页
            return true;
        } else {
            //进行登录页
            return false;
        }
    } catch (e) {
        return false;
    }
}

class MyApp extends StatefulWidget {
    MyApp(this.loginTF);

    final bool loginTF;

    @override
    State<StatefulWidget> createState() {
        return MyAppScreen(loginTF);
    }
}

class MyAppScreen extends State<MyApp> {
    MyAppScreen(this.loginTF);

    final bool loginTF;

    bool themeDataDark;

//    @override
//    void initState() {
//        //获取主题
////        getThemeData();
//        super.initState();
//    }

    getThemeData() {
        bool themeData;
        try {
            myUtils.LocalStorage.getLocalStorageInstance()
                    .then((SharedPreferences sharedPreferences) {
                themeData = sharedPreferences.getBool("themeData_dark");

                setState(() {
                    themeDataDark = themeData != null ? themeData : false;
                });
            });
        } catch (e) {
            print(e);
            setState(() {
                themeDataDark = false;
            });
        }
//    print(themeDataDark);
    }

    @override
    Widget build(BuildContext context) {
        getThemeData();

        if (themeDataDark != null) {
            return MaterialApp(
                debugShowCheckedModeBanner: false,
                //不显示右上解的"DEBUG"角标
                title: 'energy-chains',
                home: loginTF ? MainScreen() : LoginScreen(),
                theme: themeDataDark ? ThemeData.dark() : ThemeData.light(),
//    theme: ThemeData(primaryColor: Colors.deepOrange),
                routes: <String, WidgetBuilder>{
                    '/loginScreen': (BuildContext context) => LoginScreen(),
                    '/mainScreen': (BuildContext context) => MainScreen(),
                    '/homeScreen': (BuildContext context) => HomeScreen(),
                    '/mineScreen': (BuildContext context) => MineScreen(),
                    '/step_screen': (BuildContext context) => StepScreen(null),
                    '/changePwd_screen': (BuildContext context) =>
                            ChangePwdScreen(),
                    '/aboutUs': (BuildContext context) => AboutUsScreen(),
                },
            );
        }
        return Text("aa");
    }
}
